package com.redbudcloud.common;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;
import net.sf.json.util.PropertyFilter;

import java.lang.reflect.Field;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by zhxiaotong on 17-12-17.
 */
public class JsonUtil {
    // 将String转换成JSON
    public static String string4json(String key, String value) {
        JSONObject object = new JSONObject();
        object.put(key, value);
        return object.toString();
    }

    // 从一个JSON 对象字符格式中得到一个java对象
    public static Object getObjectJsonString(String jsonString, Class pojoCalss) {
        Object pojo;
        String[] formats = {"yyyy-MM-dd"};
        JSONUtils.getMorpherRegistry().registerMorpher(new TimestampMorpher(formats));
        JSONObject jsonObject = JSONObject.fromObject(jsonString);
        pojo = JSONObject.toBean(jsonObject, pojoCalss);
        return pojo;
    }

    // 从一个JSON 对象字符格式中得到一个java对象
    public static Object getObjectJsonString(JSONObject jsonObject, Class pojoClass) {
        Object pojo;
        pojo = JSONObject.toBean(jsonObject, pojoClass);
        return pojo;
    }

    //从li集合中获取json格式字符串
    public static String getJsonList(List li) {
        JsonConfig jsonConfig = new JsonConfig();   //JsonConfig是net.sf.json.JsonConfig中的这个，为固定写法
        PropertyFilter filter = new PropertyFilter() {
            public boolean apply(Object object, String fieldName, Object fieldValue) {
                boolean f = false;
                if (null == fieldValue || "".equals(fieldValue)) {
                    f = true;
                }
                return f;
            }
        };
        jsonConfig.setJsonPropertyFilter(filter);
        return JSONArray.fromObject(li, jsonConfig).toString();
    }


    public static JSONObject getJson(Object ob, final String filterStr) {
        JsonConfig jsonConfig = new JsonConfig();   //JsonConfig是net.sf.json.JsonConfig中的这个，为固定写法
        PropertyFilter filter = new PropertyFilter() {
            public boolean apply(Object object, String fieldName, Object fieldValue) {
                boolean f = false;
                if (null == fieldValue || "".equals(fieldValue)) {
                    f = true;
                }
                if (filterStr != null && filterStr.contains(fieldName)) {
                    f = true;
                }
                return f;
            }
        };
        jsonConfig.setJsonPropertyFilter(filter);
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Time.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor());
        return JSONObject.fromObject(ob, jsonConfig);
    }

    //重载
    //从li集合中获取json格式字符串
    public static JSONArray getJsonList(Object li, final String filterStr) {
        JsonConfig jsonConfig = new JsonConfig();   //JsonConfig是net.sf.json.JsonConfig中的这个，为固定写法
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        PropertyFilter filter = new PropertyFilter() {
            public boolean apply(Object object, String fieldName, Object fieldValue) {
                boolean f = false;
                if (null == fieldValue || "".equals(fieldValue)) {
                    f = true;
                }

                if (filterStr != null && filterStr.contains(fieldName)) {
                    f = true;
                }
                return f;
            }
        };
        jsonConfig.setJsonPropertyFilter(filter);
        return JSONArray.fromObject(li, jsonConfig);
    }


    // 从json对象集合表达式中得到一个java对象列表
    public static List getList4Json(String jsonString, Class pojoClass) {
        JSONArray jsonArray = JSONArray.fromObject(jsonString);
        JSONObject jsonObject;
        Object pojoValue;
        List list = new ArrayList();
        for (int i = 0; i < jsonArray.size(); i++) {
            jsonObject = jsonArray.getJSONObject(i);
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.setJavaPropertyFilter(new PropertyFilter() {
                public boolean apply(Object source, String name, Object value) {
                    try {
                        Field field = source.getClass().getDeclaredField(name);
                        if (field.getType() == Date.class) {
                            String formats[] = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "yyyy/MM/dd"};
                            if (BaseUtil.isNull((String) value)) {//过滤日期类型，但没有设置值的字段，不需要被默认设置为当前日期
                                return true;
                            } else {
                                for (String format : formats) {
                                    Date tempDate = getDateFormat((String) value, format);

                                    if (tempDate != null) {
                                        source.getClass().getMethod("set" + name.substring(0, 1).toUpperCase() + name.substring(1), Date.class).invoke(source, tempDate);
                                        break;
                                    }
                                }
                            }
                            return true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return false;
                }
            });
            jsonConfig.setRootClass(pojoClass);
            pojoValue = JSONObject.toBean(jsonObject, jsonConfig);
            list.add(pojoValue);

        }
        return list;

    }

    private static Date getDateFormat(String dateString, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(dateString);
        } catch (ParseException e) {
            return null;
        }
    }

    public static String getMap4Json(Map map) {
        JsonConfig jsonConfig = new JsonConfig();   //JsonConfig是net.sf.json.JsonConfig中的这个，为固定写法
        PropertyFilter filter = new PropertyFilter() {
            public boolean apply(Object object, String fieldName, Object fieldValue) {
                boolean f = false;
                if (null == fieldValue || "".equals(fieldValue) || "default".equals(fieldValue)) {
                    f = true;
                }
                if ("chapterses".equals(fieldName) || "mycCourses".equals(fieldName) || "sectionses".equals(fieldName)) {
                    f = true;
                }
                return f;
            }
        };
        jsonConfig.setJsonPropertyFilter(filter);
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Time.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(String.class, new JsonDateValueProcessor());
        JSONObject jsonObject = JSONObject.fromObject(map, jsonConfig);
        return jsonObject.toString();
    }

    public static String beanToJson(Object obj, String dateFormat) {
        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(Timestamp.class, new DateJsonValueProcessor(dateFormat));
        config.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor(dateFormat));
        JSONObject json = JSONObject.fromObject(obj, config);
        return json.toString();
    }

    //JSON转换过滤
    public static String getMap4Json(Map map, final String filterStr) {
        JsonConfig jsonConfig = new JsonConfig();   //JsonConfig是net.sf.json.JsonConfig中的这个，为固定写法
        PropertyFilter filter = new PropertyFilter() {
            public boolean apply(Object object, String fieldName, Object fieldValue) {
                boolean f = false;
                if (null == fieldValue || "".equals(fieldValue)) {
                    f = true;
                }
                if (filterStr.contains(fieldName)) {
                    f = true;
                }
                return f;
            }
        };
        jsonConfig.setJsonPropertyFilter(filter);
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Time.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(String.class, new JsonDateValueProcessor());
        JSONObject jsonObject = JSONObject.fromObject(map, jsonConfig);
        return jsonObject.toString();
    }

    //JSON转换过滤不过滤
    public static String getMap4JsonNoFilter(Map map) {
        JsonConfig jsonConfig = new JsonConfig();   //JsonConfig是net.sf.json.JsonConfig中的这个，为固定写法
        PropertyFilter filter = new PropertyFilter() {
            public boolean apply(Object object, String fieldName, Object fieldValue) {
                boolean f = false;
                return f;
            }
        };
        jsonConfig.setJsonPropertyFilter(filter);
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Time.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(String.class, new JsonDateValueProcessor());
        JSONObject jsonObject = JSONObject.fromObject(map, jsonConfig);
        return jsonObject.toString();
    }

    public static String getJsonByClass(Object ob) {
        JsonConfig jsonConfig = new JsonConfig();   //JsonConfig是net.sf.json.JsonConfig中的这个，为固定写法
        PropertyFilter filter = new PropertyFilter() {
            public boolean apply(Object object, String fieldName, Object fieldValue) {
                boolean f = false;
                if (null == fieldValue || "".equals(fieldValue)) {
                    f = true;
                }
                return f;
            }
        };
        jsonConfig.setJsonPropertyFilter(filter);
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyy-MM-dd"));
        jsonConfig.registerJsonValueProcessor(Time.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss"));
        JSONObject jsonObject = JSONObject.fromObject(ob, jsonConfig);
        return jsonObject.toString();
    }

    public static JSONObject getJsonOBByClass(Object ob) {
        JsonConfig jsonConfig = new JsonConfig();   //JsonConfig是net.sf.json.JsonConfig中的这个，为固定写法
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Time.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor());
        JSONObject jsonObject = JSONObject.fromObject(ob, jsonConfig);
        return jsonObject;
    }

    // 从json数组中解析出java字符串数组
    public static Object[] getStringArray4Json(String jsonString) {
        JSONObject jsonObj = JSONObject.fromObject(jsonString);
        JSONArray jsonarr = jsonObj.getJSONArray("item");
        return (Object[]) jsonarr.toArray();
    }
}
